﻿#include "widget.h"
#include "ui_widget.h"
#include<QFile>
#include<QMessageBox>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    setWindowFlag(Qt::FramelessWindowHint);
    m_sender=new QUdpSocket(this);
    m_sender->bind(6666,QUdpSocket::ShareAddress);
    connect(m_sender,&QUdpSocket::readyRead,this,&Widget::dealMsg);
    initControl();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::mousePressEvent(QMouseEvent *event)
{
    if(event->button()==Qt::LeftButton){
        m_point=event->globalPos()-mapToGlobal(QPoint(0,0));
        event->accept();
    }
}

void Widget::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons()&Qt::LeftButton){
        move(event->globalPos()-m_point);
        event->accept();
    }
}

void Widget::loadStyleStyle()
{
    QFile file(":/src/style.css");
    if(file.open(QFile::ReadOnly)){
        QString str=file.readAll();
        setStyleSheet(str);
        file.close();
    }else{
        QMessageBox::information(this,"info",QString::fromLocal8Bit("打开style.css失败!"));
    }
}

void Widget::initControl()
{
    loadStyleStyle();
    connect(ui->closeBtn,&QPushButton::clicked,[this]{
        close();
    });
    connect(ui->sendBtn,&QPushButton::clicked,[this]{
        ui->textBrowser->appendMsg(ui->textEdit->document()->toPlainText());
        m_sender->writeDatagram(ui->textEdit->document()->toPlainText().toUtf8(),QHostAddress::Broadcast,7777);
        ui->textEdit->clear();
    });
}

void Widget::dealMsg()
{
    QByteArray ret;
    ret.resize(m_sender->pendingDatagramSize());
    if(m_sender->hasPendingDatagrams()){
        m_sender->readDatagram(ret.data(),ret.size());
        ui->textBrowser->appendMsg(ret,"10001");
    }
}

